<template>
  <div>
    <el-row :gutter="12">
      <el-form ref="todoForm" :model="todoData" :rules="rules" size="mini" label-width="100px"
               label-position="top">
        <el-col :span="24">
          <el-form-item label="父待办" prop="fatherId">
            <el-select v-model="todoData.fatherId" placeholder="请选择父待办" clearable :style="{width: '100%'}"
                       :disabled="disableFatherId">
              <el-option v-for="topTodo in fatherIdOptions" :key="topTodo.id" :label="topTodo.name"
                         :value="topTodo.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="todoData.name" placeholder="请输入任务名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="type">
            <el-select v-model="todoData.type" placeholder="请选择任务类型" clearable :style="{width: '100%'}">
              <el-option style="margin-top: 10px" v-for="type in typeOptions" :key="type.code" :label="type.text"
                         :value="type.code">
                <el-tag v-if="todoData.type" :type="type.type">{{ type.text }}</el-tag>
                <div style="float: right">{{ type.name }}</div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="level">
            <el-select v-model="todoData.level" placeholder="请选择优先级" clearable :style="{width: '100%'}">
              <el-option style="margin-top: 10px" v-for="level in levelOptions" :key="level.code" :label="level.text"
                         :value="level.code">
                <el-tag v-if="todoData.level" :type="level.type">{{ level.text }}</el-tag>
                <div style="float: right">{{ level.name }}</div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="todoData.status" placeholder="请选择任务状态" clearable :style="{width: '100%'}">
              <el-option style="margin-top: 10px" v-for="status in statusOptions" :key="status.code" :label="status.text"
                         :value="status.code">
                <el-tag v-if="todoData.status" :type="status.type">{{ status.text }}</el-tag>
                <div style="float: right">{{ status.name }}</div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="deadLine">
            <el-date-picker v-model="todoData.deadLine" type="datetime"
                            :picker-options='pickerOptions' :style="{width: '100%'}"
                            placeholder="请选择截止日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计耗时" prop="cost">
            <el-input-number v-model="todoData.cost" placeholder="预计耗时" :step='1'></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务描述" prop="description">
            <el-input v-model="todoData.description" type="textarea" placeholder="请输入任务描述" :maxlength="480"
                      :autosize="{minRows: 4, maxRows: 60}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务结果" prop="result">
            <el-input v-model="todoData.result" type="textarea" placeholder="请输入任务结果" :maxlength="480"
                      :autosize="{minRows: 4, maxRows: 60}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import TodoEnum from '@/utils/todoEnum'
import {addTodo, updateTodo} from '@/api/todo'
export default {
  name: 'TodoForm',
  components: {},
  props: {
    subjectId: {
      type: [String, Number]
    },
    userId: {
      type: [String, Number]
    },
    currentFatherId: {
      type: [String, Number],
      default: undefined
    },
    fatherTodoMode: {
      type: Boolean,
      default: false
    },
    updateMode: {
      type: Boolean,
      default: false
    },
    topTodos: [Array, Object],
    currentProjectData: [Object]
  },
  data () {
    return {
      todoData: {
        fatherId: undefined,
        name: undefined,
        level: '00',
        status: '00',
        deadLine: this.getOneDayLater(),
        cost: 4,
        description: undefined,
        result: undefined,
        enable: '00',
        type: '00'
      },
      rules: {
        fatherId: [{
          required: this.fatherTodoMode,
          message: '请选择父待办',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '请输入任务名称',
          trigger: 'blur'
        }],
        level: [{
          required: true,
          message: '请选择优先级',
          trigger: 'change'
        }],
        status: [{
          required: true,
          message: '请选择任务状态',
          trigger: 'change'
        }],
        type: [{
          required: true,
          message: '请选择任务类型',
          trigger: 'change'
        }],
        deadLine: [{
          required: true,
          message: '请选择截止日期',
          trigger: 'change'
        }],
        cost: [{
          required: true,
          message: '预计耗时',
          trigger: 'blur'
        }],
        description: [{
          message: '请输入任务描述',
          trigger: 'blur'
        }],
        result: [{
          message: '请输入代办结果',
          trigger: 'blur'
        }]
      },
      fatherIdOptions: this.fatherTodos(),
      levelOptions: TodoEnum.TodoLevels,
      statusOptions: TodoEnum.TodoStatus,
      typeOptions: TodoEnum.TodoTypes,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '一天后',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周后',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      todoDataBak: undefined
    }
  },
  computed: {
    disableFatherId () {
      if (this.fatherTodoMode) {
        return false
      }
      if (this.updateMode) {
        if (this.todoData.fatherId) {
          return false
        }
      }
      return true
    }
  },
  watch: {},
  created () {
  },
  mounted () {
    if (this.fatherTodoMode) {
      this.todoData.fatherId = this.currentFatherId
    } else if (this.updateMode) {
      this.todoData.fatherId = this.currentProjectData.fatherId
      this.todoData.name = this.currentProjectData.name
      this.todoData.level = this.currentProjectData.level
      this.todoData.status = this.currentProjectData.status
      this.todoData.deadLine = this.currentProjectData.deadLine
      this.todoData.cost = this.currentProjectData.cost
      this.todoData.description = this.currentProjectData.description
      this.todoData.result = this.currentProjectData.result
      this.todoData.enable = this.currentProjectData.enable
      this.todoData.type = this.currentProjectData.type
      this.todoDataBak = this.clone(this.todoData)
    } else {
      this.todoData.fatherId = undefined
    }
  },
  methods: {
    submitForm () {
      this.$refs['todoForm'].validate(valid => {
        if (!valid) {
          return
        }
        if (!this.updateMode) {
          this.insertMode()
        } else {
          this.updateTodoMode()
        }
      })
    },
    updateTodoMode () {
      let content = {
        'userId': this.userId ? this.userId : this.$store.getters.currentUserId,
        'subjectId': this.subjectId ? this.subjectId : this.$store.getters.currentProject
      }
      this.putIfNotEqual(content, 'fatherId')
      this.putIfNotEqual(content, 'name')
      this.putIfNotEqual(content, 'level')
      this.putIfNotEqual(content, 'status')
      this.putIfNotEqual(content, 'cost')
      this.putIfNotEqual(content, 'description')
      this.putIfNotEqual(content, 'result')
      this.putIfNotEqual(content, 'enable')
      this.putIfNotEqual(content, 'type')
      content['id'] = this.currentProjectData.id
      updateTodo(content).then(() => {
        this.$notify.success('更新成功')
        this.$emit('onSubmit', this.todoData.fatherId)
        this.$emit('onCancel')
      }).catch(error => {
        this.$notify.error(error.message)
      })
    },
    putIfNotEqual (content, key) {
      if (this.todoData[key] !== this.todoDataBak[key]) {
        content[key] = this.todoData[key]
      }
    },
    insertMode () {
      let content = this.clone(this.todoData)
      content['userId'] = this.userId ? this.userId : this.$store.getters.currentUserId
      content['subjectId'] = this.subjectId ? this.subjectId : this.$store.getters.currentProject
      if (this.fatherTodoMode) {
        content['subjectId'] = this.todoData.fatherId
      }
      addTodo(content).then(() => {
        this.$notify.success('新增成功')
        this.$emit('onSubmit', this.todoData.fatherId)
        this.$emit('onCancel')
        this.resetForm()
      }).catch(error => {
        this.$notify.error({
          title: '新增失败',
          message: error.message
        })
      })
    },
    resetForm () {
      let fatherIdBak = this.todoData.fatherId
      this.$refs['todoForm'].resetFields()
      this.todoData.fatherId = fatherIdBak
    },
    getOneDayLater () {
      const date = new Date()
      return date.setTime(date.getTime() + 3600 * 1000 * 24)
    },
    clone (o) {
      if (o) {
        return JSON.parse(JSON.stringify(o))
      }
      return undefined
    },
    fatherTodos () {
      return this.topTodos ? this.topTodos : []
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
